package org.mozhu.zufang.system.privilege.entity;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.Formula;
import org.mozhu.mboot.core.data.entity.BaseEntity;
import org.mozhu.mboot.core.data.entity.Treeable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "sys_permission")
@Data
@EqualsAndHashCode(callSuper = true)
public class Permission extends BaseEntity implements Treeable<Long> {

    private static final long serialVersionUID = -6872376783695447530L;

    /**
     * 名称
     */
    private String name;

    /**
     * 描述
     */
    private String description;


    /**
     * 标识，全系统唯一
     */
    private String code;

    /**
     * 图标
     */
    private String icon;

    /**
     * 父路径
     */
    @Column(name = "parent_id")
    private Long parentId = 0L;

    @Column(name = "parent_ids")
    private String parentIds = "0/";

    /**
     * 是否有叶子节点
     */
    @Formula(value = "(select count(*) from sys_permission f_t where f_t.parent_id = id)")
    private boolean hasChildren;

    private Integer weight;

    /**
     * 是否是默认权限
     */
    @Column(name = "default_permission")
    private Boolean defaultPermission = Boolean.FALSE;
    /**
     * 是否显示
     */
    @Column(name = "is_show")
    private Boolean show = Boolean.FALSE;


    @Override
    public String makeSelfAsNewParentIds() {
        return getParentIds() + getId() + getSeparator();
    }

    @Override
    public boolean isRoot() {
        if (getParentId() != null && getParentId() == 0) {
            return true;
        }
        return false;
    }

    public String getTreetableIds() {
        String selfId = makeSelfAsNewParentIds().replace(getSeparator(), "-");
        return selfId.substring(0, selfId.length() - 1);
    }

    public String getTreetableParentIds() {
        String parentIds = getParentIds().replace(getSeparator(), "-");
        return parentIds.substring(0, parentIds.length() - 1);
    }


    public boolean isAvailable() {
        return getShow();
    }

}
